'use client'

import React, { useState } from 'react'
import { X, Copy, Share2, Lock, Edit, Users, Globe, Link } from 'lucide-react'
import { cn } from '@/lib/utils'

interface ShareModalProps {
  sheet?: any
  onClose: () => void
  onUpdate?: (updatedSheet: any) => void
}

interface ShareSettings {
  isPublic: boolean
  allowEdit: boolean
}

export function ShareModal({ sheet, onClose, onUpdate }: ShareModalProps) {
  const [shareUrl, setShareUrl] = useState('')
  const [shareToken, setShareToken] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [settings, setSettings] = useState<ShareSettings>({
    isPublic: false,
    allowEdit: false
  })

  // 生成分享链接
  const generateShareLink = async () => {
    try {
      setLoading(true)
      setError('')
      setSuccess('')

      const token = localStorage.getItem('auth_token')
      if (!token) {
        setError('请先登录')
        return
      }

      const response = await fetch(`/api/sheets/${sheet?.id}/share`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(settings)
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || '生成分享链接失败')
      }

      setShareUrl(data.shareUrl)
      setShareToken(data.shareToken)
      setSuccess('分享链接生成成功！')
    } catch (err) {
      setError(err instanceof Error ? err.message : '生成分享链接失败')
    } finally {
      setLoading(false)
    }
  }

  // 复制链接
  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl)
      setSuccess('链接已复制到剪贴板！')
    } catch (err) {
      setError('复制失败，请手动复制')
    }
  }

  // 撤销分享
  const revokeShare = async () => {
    try {
      setLoading(true)
      setError('')
      setSuccess('')

      const token = localStorage.getItem('auth_token')
      if (!token) {
        setError('请先登录')
        return
      }

      const response = await fetch(`/api/sheets/${sheet?.id}/share`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || '撤销分享失败')
      }

      setShareUrl('')
      setShareToken('')
      setSuccess('分享已撤销')
    } catch (err) {
      setError(err instanceof Error ? err.message : '撤销分享失败')
    } finally {
      setLoading(false)
    }
  }

  // 分享到其他平台
  const shareToPlatform = () => {
    if (navigator.share) {
      navigator.share({
        title: sheet?.title,
        text: `查看我的表格: ${sheet?.title}`,
        url: shareUrl
      })
    } else {
      copyLink()
    }
  }

  if (!sheet) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2">
            <Share2 size={20} className="text-blue-600" />
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              分享表格
            </h2>
          </div>
          <button
            onClick={onClose}
            className="p-1 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
          >
            <X size={20} className="text-gray-500" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 space-y-4">
          {/* 表格标题 */}
          <div className="text-sm text-gray-600 dark:text-gray-400">
            正在分享: <span className="font-medium text-gray-900 dark:text-white">{sheet?.title}</span>
          </div>

          {/* 分享设置 */}
          <div className="space-y-3">
            <h3 className="text-sm font-medium text-gray-900 dark:text-white">分享设置</h3>
            
            {/* 公开访问 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Globe size={16} className="text-gray-500" />
                <span className="text-sm text-gray-700 dark:text-gray-300">公开访问</span>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.isPublic}
                  onChange={(e) => setSettings(prev => ({ ...prev, isPublic: e.target.checked }))}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
              </label>
            </div>

            {/* 允许编辑 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Edit size={16} className="text-gray-500" />
                <span className="text-sm text-gray-700 dark:text-gray-300">允许编辑</span>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.allowEdit}
                  onChange={(e) => setSettings(prev => ({ ...prev, allowEdit: e.target.checked }))}
                  className="sr-only peer"
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
              </label>
            </div>
          </div>

          {/* 错误/成功提示 */}
          {error && (
            <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded text-red-700 dark:text-red-400 text-sm">
              {error}
            </div>
          )}
          
          {success && (
            <div className="p-3 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded text-green-700 dark:text-green-400 text-sm">
              {success}
            </div>
          )}

          {/* 分享链接 */}
          {shareUrl && (
            <div className="space-y-3">
              <h3 className="text-sm font-medium text-gray-900 dark:text-white">分享链接</h3>
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  value={shareUrl}
                  readOnly
                  className="flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                />
                <button
                  onClick={copyLink}
                  className="p-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                  title="复制链接"
                >
                  <Copy size={16} />
                </button>
              </div>
            </div>
          )}

          {/* 操作按钮 */}
          <div className="flex gap-2 pt-4">
            {!shareUrl ? (
              <button
                onClick={generateShareLink}
                disabled={loading}
                className={cn(
                  "flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded transition-colors",
                  loading
                    ? "bg-gray-300 dark:bg-gray-600 text-gray-500 cursor-not-allowed"
                    : "bg-blue-600 text-white hover:bg-blue-700"
                )}
              >
                {loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    <span>生成中...</span>
                  </>
                ) : (
                  <>
                    <Link size={16} />
                    <span>生成分享链接</span>
                  </>
                )}
              </button>
            ) : (
              <>
                <button
                  onClick={shareToPlatform}
                  className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
                >
                  <Share2 size={16} />
                  <span>分享</span>
                </button>
                <button
                  onClick={revokeShare}
                  disabled={loading}
                  className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors disabled:opacity-50"
                >
                  撤销
                </button>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
